<?php
/**
 * Created by PhpStorm.
 * User: luoshuqi
 * Date: 19-2-15
 * Time: 上午10:10
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\SysToken;
use App\Models\SysUser;
use App\Utils\CaptchaTrait;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use CaptchaTrait;

    /**
     * 登录
     * @param Request $request
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        //检查验证码
        if ($this->displayCaptcha()) {
            $captcha = $request->json('captcha');
            $signature = $request->json('signature');
            if (!$captcha || !$signature) {
                return $this->invalidParameter();
            }
            if (!$this->verifyCaptcha($captcha, $signature)) {
                return $this->error('验证码错误');
            }
        }

        list('username' => $username, 'password' => $password) =
            $this->required($request, 'username', 'password');

        $user = SysUser::findByUsername($username);
        if (!$user) {
            return $this->error('用户不存在');
        }
        if (!$user->verifyPassword($password)) {
            return $this->error('密码错误');
        }
        if (!$user['enabled']) {
            return $this->error('账号已停用');
        }

        return $this->ok(['token' => SysToken::generate($user['id'])]);
    }
}